package com.rzjm.exercise.common.shiro;

import java.util.Date;
import java.util.Set;

import com.rzjm.exercise.common.context.SpringContextHolder;
import com.rzjm.exercise.common.utils.ShiroUtils;
import com.rzjm.exercise.module.domain.Shop;
import com.rzjm.exercise.module.service.ShopService;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.rzjm.exercise.sys.system.menu.service.MenuService;
import com.rzjm.exercise.sys.system.user.dao.UserDao;
import com.rzjm.exercise.sys.system.user.domain.UserDO;

public class UserRealm extends AuthorizingRealm {
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		Integer userId = ShiroUtils.getUserId();
		MenuService menuService = SpringContextHolder.getBean(MenuService.class);
		Set<String> perms = menuService.listPerms(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());

		UserService userMapper = SpringContextHolder.getBean(UserService.class);
		ShopService shopService = SpringContextHolder.getBean(ShopService.class);
		// 查询用户信息
		UserDO user = userMapper.selectByUniqueColumn("username", username);

		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		// 密码错误
		if (!password.equals(user.getPassword())) {
			throw new IncorrectCredentialsException("账号或密码不正确");
		}

		// 账号锁定
		if (user.getStatus() == 0) {
			throw new LockedAccountException("账号已被禁用");
		}
		Shop shop = shopService.findById(user.getShopId());
		if (shop != null && shop.getState() != null && shop.getState() == 0){
			throw new LockedAccountException("该账号所在企业已被禁用");
		}
		UserDO updateUser = new UserDO();
		updateUser.setUserId(user.getUserId());
		updateUser.setLastLoginTime(new Date());
		
		userMapper.updateById(updateUser);
		
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
		return info;
	}

}
